package utils

import (
	"reflect"
	"strings"
)

// CamelCaseToSnakeCase 驼峰(含帕斯卡)转蛇形 helloWorld/HelloWorld => hello_world
func CamelCaseToSnakeCase(str string) string {
	if str == "" {
		return str
	}
	strLen := len(str)
	result := make([]byte, 0, strLen*1)
	j := false
	for i := 0; i < strLen; i++ {
		char := str[i]
		if i > 0 && char >= 'A' && char <= 'Z' && j {
			result = append(result, '_')
		}
		if char != '_' {
			j = true
		}
		result = append(result, char)
	}
	str = strings.ToLower(string(result))
	return str
}

func MyStruct2Map(obj interface{}) map[string]interface{} {
	obj_v := reflect.ValueOf(obj)
	v := obj_v.Elem()
	typeOfType := v.Type()
	var data = make(map[string]interface{})
	for i := 0; i < v.NumField(); i++ {
		field := v.Field(i)
		if !strings.HasPrefix(typeOfType.Field(i).Name, "XXX_") {
			data[CamelCaseToSnakeCase(typeOfType.Field(i).Name)] = field.Interface()
		}
	}
	return data
}
